package data

import (
	"context"
	orderV1 "shop-demo/api/order/v1"
	"shop-demo/app/shop/admin/internal/biz"
)

type orderRepo struct {
	data *Data
}

func NewOrderRepo(data *Data) biz.OrderRepo {
	return &orderRepo{data: data}
}

func (o *orderRepo) CreateOrder(ctx context.Context, order *biz.Order) (*biz.Order, error) {

	products := make([]*orderV1.CreateOrderReq_Product, 0, len(order.Details))

	for _, detail := range order.Details {
		products = append(products, &orderV1.CreateOrderReq_Product{
			Id:   detail.Id,
			Num:  detail.Num,
			Name: detail.Name,
		})
	}

	reply, err := o.data.orderClient.CreateOrder(ctx, &orderV1.CreateOrderReq{
		UserId:   order.UserId,
		Products: products,
	})

	if err != nil {
		return nil, err
	}

	return &biz.Order{
		Id:     reply.Id,
		UserId: reply.UserId,
	}, nil
}

func (o *orderRepo) GetOrder(ctx context.Context, id int64) (*biz.Order, error) {
	reply, err := o.data.orderClient.GetOrder(ctx, &orderV1.GetOrderReq{
		Id: id,
	})

	if err != nil {
		return nil, err
	}

	return &biz.Order{
		Id:     reply.Id,
		UserId: reply.UserId,
	}, nil
}

func (o *orderRepo) ListOrder(ctx context.Context, pageNum int, pageSize int) ([]*biz.Order, error) {
	reply, err := o.data.orderClient.ListOrder(ctx, &orderV1.ListOrderReq{
		Uid:      0,
		PageNum:  int64(pageNum),
		PageSize: int64(pageSize),
	})
	if err != nil {
		return nil, err
	}
	result := make([]*biz.Order, 0, len(reply.Orders))
	for _, orderElem := range reply.Orders {
		bizOrder := &biz.Order{
			Id:     orderElem.Id,
			UserId: orderElem.UserId,
			//Details: make([]*biz.Product, 0, len(orderElem.Edges.Details)),
		}
		result = append(result, bizOrder)
		//for _, detail := range orderElem.Edges.Details {
		//	bizOrder.Details = append(bizOrder.Details, &biz.Product{
		//		Id:   detail.ProductID,
		//		Name: detail.ProductName,
		//		Num:  detail.ProductNum,
		//	})
		//}
	}

	return result, nil
}
